/***********************************************************
 *
 * Gaoth
 * Copyright (c) 2011- Marcus Lundgren
 * 
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from
 * the use of this software.
 * 
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it freely,
 * subject to the following restrictions:
 *
 *  1. The origin of this software must not be misrepresented; you must not
 *     claim that you wrote the original software. If you use this software
 *     in a product, an acknowledgment in the product documentation would be
 *     appreciated but is not required.
 *
 *  2. Altered source versions must be plainly marked as such,
 *     and must not be misrepresented as being the original software.
 *
 *  3. This notice may not be removed or altered from any source distribution.
 *
 ***********************************************************/

#include "server.h"

#include <SFML/System.hpp>
#include <iostream>

Server::Server()
{
    _model = new Model();
    _net_mgr = new NetworkManager( _model );
    _net_man_thread = new NetworkManagerThread( _net_mgr );
}

Server::~Server()
{
    _net_man_thread->terminate();
    
    delete _net_man_thread;
    delete _net_mgr;
    delete _model;
}

void Server::start()
{
    //bool is_still_running = true;
    sf::Clock clock;
    
    // Start the thread that listens to updates from the network
    _net_man_thread->launch();
    
    // TODO
    // - Make the loop infinite
    //int i = 0;
    
   // const float update_freq = 0.01f;
    //float time_elapsed = 0.f;

    float time = 0;
    float current_time = 0;
    float time_between_updates = 0.2f;

    while( 1 )
    {
        //sf::Sleep( 0.001f );
        time = clock.restart().asSeconds();
        current_time += time;

        if( current_time < time_between_updates )
            continue;
        
        current_time = 0;

        //std::cout << "UPDATE: " << 1.f / time << "\n";
        
        // Input
        // Network
        // Model
        _model->update( time );
        // Update the clients
        _net_mgr->send_updates();
       // time_elapsed = 0.f;
    }
}
